import wepy from 'wepy';
import WxUtils from './WxUtils'

// HTTP工具类
export default class http {
  static token = wepy.$instance.globalData.token;
  static baseUrl = wepy.$instance.globalData.baseUrl;
  static excludeUrl =  ['get_user_favorite_by_productid','user_reg'];//排除需要登录的url

  static async request (method, url, data, loading = true) {
    const param = {
      url: this.baseUrl+url,
      method: method,
      data: data
    };
    if (loading) {
      // Tips.loading();
    }
    console.info(`[http]request url=${url}`)
    const res = await wepy.request(param);
    if (this.isSuccess(res)) {
      return res.data.data;
    } else {
      let exUrl = this.excludeUrl.filter(m => url.indexOf(m) > -1)
      if(exUrl == null || exUrl == undefined || exUrl == '')this.isNeedLogin(res);
      console.log("[数据异常]"+res.data.message)
      // throw this.requestException(res);
    }
  }

  static isNeedLogin (res) {
    const wxData = res.data;
    const code = wxData.code
    if(code == -2) {
      wx.navigateTo({url: "/pages/home/login_phone"});
      // WxUtils.backOrNavigate()
    }
  }
  /**
   * 判断请求是否成功
   */
  static isSuccess (res) {
    const wxCode = res.statusCode;
    // 微信请求错误
    if (wxCode !== 200) {
      return false;
    }
    const wxData = res.data;
    return !(wxData && wxData.code !== 200);
  }

  /**
   * 异常
   */
  static requestException (res) {
    const error = {};
    error.statusCode = res.statusCode;
    const wxData = res.data;
    const serverData = wxData.data;
    if (serverData) {
      error.serverCode = wxData.code;
      error.message = serverData.message;
      error.serverData = serverData;
    }
    return error;
  }
  
  /**
   * 构造上传文件头部
   */
  static createAuthHeader () {
    let token = wepy.$instance.globalData.token;
    const header = {};
    header['Content-Type'] = 'multipart/form-data'
    if(token == null || token == undefined || token == '')
      token = wepy.getStorageSync("token")
    if (token) {
      header['token'] = token;
    }
    return header;
  }
  
  static get (url, data, loading = true) {
    return this.request('GET', url, data, loading);
  }

  static put (url, data, loading = true) {
    return this.request('PUT', url, data, loading);
  }

  static post (url, data, loading = true) {
    return this.request('POST', url, data, loading);
  }

  static patch (url, data, loading = true) {
    return this.request('PATCH', url, data, loading);
  }

  static delete (url, data, loading = true) {
    return this.request('DELETE', url, data, loading);
  }
}
